package com.example.secondhandshop.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.secondhandshop.R;
import com.example.secondhandshop.bean.ResponseBody;
import com.example.secondhandshop.bean.User;
import com.example.secondhandshop.utils.UserManagerUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginAcitivity extends AppCompatActivity {
    private Boolean bPwdshow=false;
    private EditText etPwd;
    private EditText etuser;
    private CheckBox etpwd_check;
    private Button btn_login;
    private TextView textsignup;
    public static int userid;
    public int money;
    private Login_back loginBack;

    private final Gson gson = new Gson();
    public static class ResponseBody <T> {
        /**
         * 业务响应码
         */
        private int code;
        /**
         * 响应提示信息
         */
        private String msg;
        /**
         * 响应数据
         */
        private T data;

        public ResponseBody(){}

        public int getCode() {
            return code;
        }
        public String getMsg() {
            return msg;
        }
        public T getData() {
            return data;
        }

        @NonNull
        @Override
        public String toString() {
            return "ResponseBody{" +
                    "code=" + code +
                    ", msg='" + msg + '\'' +
                    ", data=" + data +
                    '}';
        }
    }
    private void sendCredentialsToServer(String username, String password) { //将账号密码传入后端
        OkHttpClient client = new OkHttpClient();
        String url = Constans.SERVER_URL()+"tran/user/login";
        Headers headers = new Headers.Builder()
                .add("appId", Constans.getAppId())
                .add("appSecret", Constans.getAppSecret())
                .add("Accept", "application/json, text/plain, */*")
                .build();
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("password",password);
        bodyMap.put("username", username);
        // 将Map转换为字符串类型加入请求体中
        Gson gson=new Gson();
        String body = gson.toJson(bodyMap);
        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                .build();
            client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("网络请求", "请求失败： " + e.getMessage());
                System.out.println("失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.i("网络请求", "请求成功，状态码： " + response.code());
                    Type jsonType = new TypeToken<ResponseBody<Login_back>>(){}.getType();
                    // 获取响应体的json串
                    String body = response.body().string();
                    Log.d("info", body);
                    // 解析json串到自己封装的状态
                    ResponseBody<Login_back> loginBackResponseBody = gson.fromJson(body,jsonType);
                    System.out.println(loginBackResponseBody.toString());
                    Log.d("LoginActivity", loginBackResponseBody.toString());
                    Login_back login_back=loginBackResponseBody.getData();
                    userid=login_back.id;
                    money=login_back.getMoney();
                    System.out.println(getResources().getString(R.string.sharepreferences_filename));
                    SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.sharepreferences_filename), MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putInt("money", money); // 存储 money
                    editor.apply();
                    Intent intent2=new Intent(LoginAcitivity.this, MainActivity.class);
                    startActivity(intent2);
                    System.out.println(userid);
                    Intent intent=new Intent(LoginAcitivity.this, MainActivity.class);
                    startActivity(intent);
                }
            }
        });
    }
    @SuppressLint("MissingInflatedId")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        final ImageView passshow=findViewById(R.id.pwd_show);
        etPwd=findViewById(R.id.password);
        etuser=findViewById(R.id.user);
        etpwd_check=findViewById(R.id.pwd_remember);
        btn_login=findViewById(R.id.login);
        textsignup=findViewById(R.id.signup);
        String spfilename=getResources().getString(R.string.sharepreferences_filename);
        String login_user=getResources().getString(R.string.login_user);
        String login_pwd=getResources().getString(R.string.login_pwd);
        String pwd_check=getResources().getString(R.string.pwd_check);

        SharedPreferences sharedPreferences=getSharedPreferences(spfilename,MODE_PRIVATE);
        String user=sharedPreferences.getString(login_user,null);
        String password=sharedPreferences.getString(login_pwd,null);

        Boolean rememberpwd=sharedPreferences.getBoolean(pwd_check,false);
        if(user!=null| TextUtils.isEmpty(user)){
            etuser.setText(user);
        }
        if(password!=null| TextUtils.isEmpty(password)){
            etPwd.setText(password);
        }
        etpwd_check.setChecked(rememberpwd);
        passshow.setOnClickListener(new View.OnClickListener() {//密码是否展示
            @Override
            public void onClick(View view) {
                bPwdshow=!bPwdshow;
                if(bPwdshow){
                    passshow.setImageResource(R.drawable.baseline_visibility_24);
                    etPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                else {
                    passshow.setImageResource(R.drawable.baseline_visibility_off_24);
                    etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    etPwd.setTypeface(Typeface.DEFAULT);
                }

            }
        });
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences.Editor editor=sharedPreferences.edit();
                if(etpwd_check.isChecked()){
                    String password=etPwd.getText().toString();
                    String user=etuser.getText().toString();
                    editor.putString(login_user,user);
                    editor.putString(login_pwd,password);
                    editor.putBoolean(pwd_check, true);
                    editor.apply();
                    sendCredentialsToServer(user,password);
                }
                else{
                    editor.remove(login_user);
                    editor.remove(login_pwd);
                    editor.remove(pwd_check);
                    editor.apply();
                }

            }
        });
        textsignup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(LoginAcitivity.this, SignupActivity.class);
                startActivity(intent);
            }
        });

    }
}